package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.mapper.CourseSchedulingDetailMapper;
import com.xmy.cultivate.mapper.OrderDetailMapper;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.mapper.StudentMapper;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class WeiChartServiceImpl implements IWeiChartService {

    @Autowired
    ITranscriptService iTranscriptService;

    @Autowired
    IWecharsBindService iWecharsBindService;

    @Autowired
    IWecharsPushLogService iWecharsPushLogService;

    @Autowired
    ITranscriptWritePushLogService iTranscriptWritePushLogService;

    @Autowired
    @Lazy
    ITranscriptWritePushSetService iTranscriptWritePushSetService;

    @Autowired
    IStudentService iStudentService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ITranscriptSetService iTranscriptSetService;

    @Autowired
    CourseSchedulingDetailMapper courseSchedulingDetailMapper;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    IdWorker idWorker;

    @Override
    @Async("onlineAsync")
    public void pushAction(Long studentId, Quarter quarter, Integer weicharPushCount, TranscriptSet transcriptSet) throws InterruptedException {
        //Thread.sleep(100);
        //System.out.println("线程" + Thread.currentThread().getName() + " 执行异步任务：" + studentId);

        /**
         * 0发送测试，1正式发送
         */
        QueryWrapper<WecharsBind> wecharsBindQueryWrapper = new QueryWrapper<>();
        wecharsBindQueryWrapper.eq("student_id",studentId);
        List<WecharsBind> wecharsBindList = new ArrayList<>();
        if (transcriptSet.getPushType().equals(1)){
            wecharsBindList = iWecharsBindService.list(wecharsBindQueryWrapper);
        }else {
            if (StringUtils.isNotBlank(transcriptSet.getPushOpenids())){
                String[] strArray = transcriptSet.getPushOpenids().split(",");
                List<String> openidList = Arrays.asList(strArray);
                WecharsBind wecharsBind;
                for (String str:openidList){
                    wecharsBind = new WecharsBind();
                    wecharsBind.setOpenid(str);
                    wecharsBindList.add(wecharsBind);
                }
            }
        }

        //System.out.println("transcriptPush");

        /*List<String> openIdList = new ArrayList<>();
        openIdList.add("oRIol5oemCb0ukQma_2UtRm_hjhA");
        openIdList.add("oRIol5iPFMLiXpwdAOlt821PsHHw");
        openIdList.add("oRIol5p6Z2-MujW7w3J1BpZa9XzU");*/
        for (WecharsBind wecharsBind:wecharsBindList){
            /*if (!openIdList.contains(wecharsBind.getOpenid())){
                log.info("不推送:"+wecharsBind.getOpenid());
                continue;
            }*/

            QueryWrapper<WecharsPushLog> wecharsPushLogQueryWrapper = new QueryWrapper<>();
            wecharsPushLogQueryWrapper.eq("openid",wecharsBind.getOpenid());
            wecharsPushLogQueryWrapper.eq("year_part",quarter.getYearPart());
            wecharsPushLogQueryWrapper.eq("quarter_num",quarter.getNum());
            wecharsPushLogQueryWrapper.eq("type",1);
            wecharsPushLogQueryWrapper.eq("count",weicharPushCount);
            Long count = iWecharsPushLogService.count(wecharsPushLogQueryWrapper);
            if (count>0){
                continue;
            }

            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.inSql("id","select student_id from wechars_bind where openid = '"+wecharsBind.getOpenid()+"' ");
            studentQueryWrapper.groupBy("name");
            List<Student> studentList = iStudentService.list(studentQueryWrapper);
            StringBuilder stringBuilder = new StringBuilder();
            List<Long> studentIdList = new ArrayList<>();
            for (Student student:studentList){
                stringBuilder.append(student.getName()).append(",");
                studentIdList.add(student.getId());
            }

            //System.out.println("开始推送");
            String url = "http://jz.5ixmy.xyz";
            if (stringBuilder.length() >0){
                stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
                StringBuilder first = new StringBuilder();
                first.append(stringBuilder.toString()+"家长，您好！请点击填写孩子本次学校考试的成绩");
                //LocalDate currentDate = LocalDate.now();
                String keyword1 = String.valueOf(quarter.getYearPart())+"年";
                StringBuilder keyword2 = new StringBuilder();
                keyword2.append(quarter.getAliasName());
                StringBuilder keyword3 = new StringBuilder();
                keyword3.append(stringBuilder.toString());
                StringBuilder remark = new StringBuilder();
                remark.append("如有疑问，请与老师联系");
                //List<String> opendIdList = iWecharsBindService.getSendOpenid(wecharsBind.getStudentId());
                List<String> opendIdList = new ArrayList<>();
                opendIdList.add(wecharsBind.getOpenid());
                boolean rs = iWecharsBindService.wxPushPartriach(opendIdList,first.toString(),keyword1,keyword2.toString(),keyword3.toString(),remark.toString(),url,String.valueOf(Math.random()));

                //添加到推送记录
                QueryWrapper<WecharsPushLog> wecharsPushLogQueryWrapperAdd = new QueryWrapper<>();
                wecharsPushLogQueryWrapperAdd.eq("year_part",quarter.getYearPart());
                wecharsPushLogQueryWrapperAdd.eq("quarter_num",quarter.getNum());
                wecharsPushLogQueryWrapperAdd.eq("type",1);
                wecharsPushLogQueryWrapperAdd.eq("openid",wecharsBind.getOpenid());
                wecharsPushLogQueryWrapperAdd.last(" limit 1");
                WecharsPushLog wecharsPushLog = iWecharsPushLogService.getOne(wecharsPushLogQueryWrapperAdd);
                if (wecharsPushLog == null){
                    wecharsPushLog = new WecharsPushLog();
                    wecharsPushLog.setId(idWorker.nextId());
                    wecharsPushLog.setAddDate(LocalDate.now());
                    wecharsPushLog.setYearPart(quarter.getYearPart());
                    wecharsPushLog.setQuarterNum(quarter.getNum());
                    wecharsPushLog.setContent(stringBuilder.toString());
                    wecharsPushLog.setRemark("成绩统计推送");
                    wecharsPushLog.setType(1);
                    wecharsPushLog.setCount(weicharPushCount);
                    wecharsPushLog.setOpenid(wecharsBind.getOpenid());
                    iWecharsPushLogService.save(wecharsPushLog);
                }else {
                    wecharsPushLog.setCount(weicharPushCount);
                    iWecharsPushLogService.updateById(wecharsPushLog);
                }
            }
        }
    }

    /**
     * 单次成绩推送
     */
    @Override
    @Async("onlineAsync")
    public void scorePush(Long writePushSetId,Long studentId, Quarter quarter) throws InterruptedException {
        //Thread.sleep(100);
        //System.out.println("线程" + Thread.currentThread().getName() + " 执行异步任务：" + studentId);

        /**
         * 0发送测试，1正式发送
         */
        QueryWrapper<WecharsBind> wecharsBindQueryWrapper = new QueryWrapper<>();
        wecharsBindQueryWrapper.eq("student_id",studentId);
        List<WecharsBind> wecharsBindList = iWecharsBindService.list(wecharsBindQueryWrapper);
        for (WecharsBind wecharsBind:wecharsBindList){

            QueryWrapper<TranscriptWritePushSet> transcriptWritePushSetQueryWrapper = new QueryWrapper<>();
            transcriptWritePushSetQueryWrapper.eq("id",writePushSetId);
            transcriptWritePushSetQueryWrapper.last("limit 1");
            TranscriptWritePushSet transcriptWritePushSet = iTranscriptWritePushSetService.getOne(transcriptWritePushSetQueryWrapper);

            QueryWrapper<TranscriptWritePushLog> transcriptWritePushLogQueryWrapper = new QueryWrapper<>();
            transcriptWritePushLogQueryWrapper.eq("student_id",studentId);
            transcriptWritePushLogQueryWrapper.eq("write_push_set_id",writePushSetId);
            transcriptWritePushLogQueryWrapper.eq("openid",wecharsBind.getOpenid());
            transcriptWritePushLogQueryWrapper.eq("push_type",1);
            if (transcriptWritePushSet != null) {
                if (transcriptWritePushSet.getPushTimes() != null) {
                    transcriptWritePushLogQueryWrapper.eq("push_time", transcriptWritePushSet.getPushTimes());
                }
                if (transcriptWritePushSet.getStartDate() != null) {
                    transcriptWritePushLogQueryWrapper.eq("push_date", transcriptWritePushSet.getStartDate());
                }
            }
            long count = iTranscriptWritePushLogService.count( transcriptWritePushLogQueryWrapper);
            if (count>0){
                continue;
            }

            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.inSql("id","select student_id from wechars_bind where openid = '"+wecharsBind.getOpenid()+"' ");
            studentQueryWrapper.groupBy("name");
            List<Student> studentList = iStudentService.list(studentQueryWrapper);
            StringBuilder stringBuilder = new StringBuilder();
            List<Long> studentIdList = new ArrayList<>();
            for (Student student:studentList){
                stringBuilder.append(student.getName()).append(",");
                studentIdList.add(student.getId());
            }

            //System.out.println("开始推送");
            String url = "http://jz.5ixmy.xyz?pushId="+writePushSetId;
            if (stringBuilder.length() >0){
                stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
                StringBuilder first = new StringBuilder();
                first.append(stringBuilder.toString()+"家长，您好！请点击填写孩子本次学校考试的成绩");
                //LocalDate currentDate = LocalDate.now();
                String keyword1 = String.valueOf(quarter.getYearPart())+"年";
                StringBuilder keyword2 = new StringBuilder();
                keyword2.append(quarter.getAliasName());
                StringBuilder keyword3 = new StringBuilder();
                keyword3.append(stringBuilder.toString());
                StringBuilder remark = new StringBuilder();
                remark.append("如有疑问，请与老师联系");
                List<String> opendIdList = new ArrayList<>();
                opendIdList.add(wecharsBind.getOpenid());
                boolean rs = iWecharsBindService.wxPushPartriach(opendIdList,first.toString(),keyword1,keyword2.toString(),keyword3.toString(),remark.toString(),url,String.valueOf(Math.random()));

                //添加到单次推送记录
                TranscriptWritePushLog transcriptWritePushLog = new TranscriptWritePushLog();
                transcriptWritePushLog.setId(idWorker.nextId());
                transcriptWritePushLog.setWritePushSetId(writePushSetId);
                transcriptWritePushLog.setStudentId(studentId);
                transcriptWritePushLog.setOpenid(wecharsBind.getOpenid());
                transcriptWritePushLog.setPushTime(transcriptWritePushSet.getPushTimes());
                transcriptWritePushLog.setPushType(1);
                transcriptWritePushLog.setPushDate(transcriptWritePushSet.getStartDate());

                iTranscriptWritePushLogService.save(transcriptWritePushLog);
            }
        }
    }

    /**
     * 定时成绩推送
     */
    @Override
    @Async("onlineAsync")
    public void scoreScheduledPush(String pushTime,LocalDate pushDate,Long writePushSetId,Long studentId, Quarter quarter) throws InterruptedException {

        /**
         * 0发送测试，1正式发送
         */
        QueryWrapper<WecharsBind> wecharsBindQueryWrapper = new QueryWrapper<>();
        wecharsBindQueryWrapper.eq("student_id",studentId);
        List<WecharsBind> wecharsBindList = iWecharsBindService.list(wecharsBindQueryWrapper);



        for (WecharsBind wecharsBind:wecharsBindList){

            QueryWrapper<TranscriptWritePushLog> transcriptWritePushLogQueryWrapper1 = new QueryWrapper<>();
            transcriptWritePushLogQueryWrapper1.eq("student_id",studentId);
            transcriptWritePushLogQueryWrapper1.eq("write_push_set_id",writePushSetId);
            transcriptWritePushLogQueryWrapper1.eq("openid",wecharsBind.getOpenid());
            transcriptWritePushLogQueryWrapper1.eq("push_date",pushDate);
            transcriptWritePushLogQueryWrapper1.eq("push_time",pushTime);
            transcriptWritePushLogQueryWrapper1.eq("push_type",2);
            //System.out.println("studentId=="+studentId);
            //System.out.println("write_push_set_id=="+writePushSetId);
            //System.out.println("openid=="+wecharsBind.getOpenid());
            //System.out.println("push_date=="+pushDate);
            //System.out.println("push_time=="+pushTime);

            long count = iTranscriptWritePushLogService.count(transcriptWritePushLogQueryWrapper1);
            if (count>0){
                continue;
            }
            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.inSql("id","select student_id from wechars_bind where openid = '"+wecharsBind.getOpenid()+"' ");
            studentQueryWrapper.groupBy("name");
            List<Student> studentList = iStudentService.list(studentQueryWrapper);
            StringBuilder stringBuilder = new StringBuilder();
            List<Long> studentIdList = new ArrayList<>();
            for (Student student:studentList){
                stringBuilder.append(student.getName()).append(",");
                studentIdList.add(student.getId());
            }

            //System.out.println("开始推送");
            String url = "http://jz.5ixmy.xyz?pushId="+writePushSetId;
            if (stringBuilder.length() >0){
                stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
                StringBuilder first = new StringBuilder();
                first.append(stringBuilder.toString()+"家长，您好！请点击填写孩子本次学校考试的成绩");
                //LocalDate currentDate = LocalDate.now();
                String keyword1 = String.valueOf(quarter.getYearPart())+"年";
                StringBuilder keyword2 = new StringBuilder();
                keyword2.append(quarter.getAliasName());
                StringBuilder keyword3 = new StringBuilder();
                keyword3.append(stringBuilder.toString());
                StringBuilder remark = new StringBuilder();
                remark.append("如有疑问，请与老师联系");
                List<String> opendIdList = new ArrayList<>();
                opendIdList.add(wecharsBind.getOpenid());
                boolean rs = iWecharsBindService.wxPushPartriach(opendIdList,first.toString(),keyword1,keyword2.toString(),keyword3.toString(),remark.toString(),url,String.valueOf(Math.random()));

                //添加到定时推送记录
                TranscriptWritePushLog transcriptWritePushLog = new TranscriptWritePushLog();
                transcriptWritePushLog.setId(idWorker.nextId());
                transcriptWritePushLog.setWritePushSetId(writePushSetId);
                transcriptWritePushLog.setStudentId(studentId);
                transcriptWritePushLog.setOpenid(wecharsBind.getOpenid());
                transcriptWritePushLog.setPushTime(pushTime);
                transcriptWritePushLog.setPushDate(pushDate);;
                transcriptWritePushLog.setPushType(2);
                iTranscriptWritePushLogService.save(transcriptWritePushLog);
            }
        }
    }



    @Override
    public void attendClassRemind() {
        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        LocalDate localDate = LocalDate.now().plusDays(1);
        repairCourseQueryWrapper.eq("school_date", localDate);
        repairCourseQueryWrapper.eq("status", 0);

        List<RepairCourse> repairCourseList = courseSchedulingDetailMapper.getSchedulingUnionRepair(repairCourseQueryWrapper);

        //System.out.println("repairCourseListCount:"+repairCourseList.size());

        for (RepairCourse repairCourse : repairCourseList) {
            try {
                if (!repairCourse.getLessonType().equals(1)) {
                    continue;
                }

                //1按班级正常排课、调课，2按学员调课、补课，消课
                if (repairCourse.getSchedulingType().equals(1)) {
                    //课程类别：1精品课，2智能课，3补课，4调课，5消课
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("grade_id", repairCourse.getGradeId());
                    studentGradeQueryWrapper.eq("reading_status", 1);
                    studentGradeQueryWrapper.eq("status", 1);
                    studentGradeQueryWrapper.eq("deleted", 0);
                    studentGradeQueryWrapper.notInSql("student_id", "select student_id from repair_course where deleted=0 and out_scheduling_detail_id=" + repairCourse.getId() + "");
                    studentGradeQueryWrapper.groupBy("student_id");
                    List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
                    //System.out.println("studentGradeListCount:"+studentGradeList.size());
                    for (StudentGrade studentGrade : studentGradeList) {
                        Integer yearAndQuarter = Integer.parseInt(studentGrade.getYearPart() + "" + studentGrade.getQuarterNum());
                        Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(studentGrade.getSchoolId(), studentGrade.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, studentGrade.getLessonType());
                        if (residueCourseCount > 0) {
                            Student student = studentMapper.selectById(studentGrade.getStudentId());
                            if (student != null) {
                                if (repairCourse.getCourseType().equals(1)) {
                                    //班级里的上课学生
                                    StringBuilder first = new StringBuilder();
                                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”上课提醒");

                                    //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                                    String keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());

                                    StringBuilder keyword2 = new StringBuilder();
                                    keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                                    StringBuilder remark = new StringBuilder();
                                    remark.append("如有疑问，请与老师联系");
                                    List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                                    iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                                } else {
                                    //班级里的调课学生
                                    StringBuilder first = new StringBuilder();
                                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”上课提醒");
                                    String keyword1 = "";
                                    if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                                        keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                                    } else {
                                        //String teacherName =  studentGradeMapper.getTeacherNameForGradeId(studentGrade.getGradeId());
                                        keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();

                                    }

                                    StringBuilder keyword2 = new StringBuilder();
                                    keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                                    StringBuilder remark = new StringBuilder();
                                    remark.append("如有疑问，请与老师联系");
                                    List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                                    iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                                }
                            }
                        }


                    }
                } else if (repairCourse.getSchedulingType().equals(2)) {
                    Integer yearAndQuarter = Integer.parseInt(repairCourse.getYearPart() + "" + repairCourse.getQuarter());
                    Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(repairCourse.getSchoolId(), repairCourse.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, repairCourse.getLessonType());
                    if (residueCourseCount > 0) {
                        Student student = studentMapper.selectById(repairCourse.getStudentId());
                        if (student != null) {
                            StringBuilder first = new StringBuilder();
                            first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”上课提醒");

                            String keyword1 = "";
                            if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                                keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                            } else {
                                keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();
                                try {
                                    RecordCourse recordCourse = studentGradeMapper.getLastReadingGrade(repairCourse.getYearPart(), repairCourse.getQuarter(), repairCourse.getSchoolId(), repairCourse.getSubjectsId(), repairCourse.getStudentId());
                                    String gradeName = recordCourse.getGradeName();
                                    gradeName = this.replaceGradeName(gradeName, recordCourse.getTeacherName(),student.getName(), repairCourse.getSubjectsName());
                                    keyword1 = gradeName;
                                } catch (Exception e) {
                                }
                            }

                            StringBuilder keyword2 = new StringBuilder();
                            keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                            StringBuilder remark = new StringBuilder();
                            remark.append("如有疑问，请与老师联系");
                            List<String> opendIdList = iWecharsBindService.getSendOpenid(repairCourse.getStudentId());
                            iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                        }
                    }
                }
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void cancClassRemind(){
        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        LocalDate localDate = LocalDate.now().plusDays(1);
        repairCourseQueryWrapper.eq("school_date", localDate);
        repairCourseQueryWrapper.eq("status", 2);

        List<RepairCourse> repairCourseList = courseSchedulingDetailMapper.getSchedulingUnionRepair(repairCourseQueryWrapper);

        //System.out.println("repairCourseListCount:"+repairCourseList.size());

        for (RepairCourse repairCourse : repairCourseList) {
            try {
                if (!repairCourse.getLessonType().equals(1)) {
                    continue;
                }

                //1按班级正常排课、调课，2按学员调课、补课，消课
                if (repairCourse.getSchedulingType().equals(1)) {
                    //课程类别：1精品课，2智能课，3补课，4调课，5消课
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("grade_id", repairCourse.getGradeId());
                    studentGradeQueryWrapper.eq("reading_status", 1);
                    studentGradeQueryWrapper.eq("status", 1);
                    studentGradeQueryWrapper.eq("deleted", 0);
                    studentGradeQueryWrapper.notInSql("student_id", "select student_id from repair_course where deleted=0 and out_scheduling_detail_id=" + repairCourse.getId() + "");
                    studentGradeQueryWrapper.groupBy("student_id");
                    List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
                    //System.out.println("studentGradeListCount:"+studentGradeList.size());
                    for (StudentGrade studentGrade : studentGradeList) {
                        Integer yearAndQuarter = Integer.parseInt(studentGrade.getYearPart() + "" + studentGrade.getQuarterNum());
                        Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(studentGrade.getSchoolId(), studentGrade.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, studentGrade.getLessonType());
                        if (residueCourseCount > 0) {
                            Student student = studentMapper.selectById(studentGrade.getStudentId());
                            if (student != null) {
                                if (repairCourse.getCourseType().equals(1)) {
                                    //班级里的上课学生
                                    StringBuilder first = new StringBuilder();
                                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”");

                                    //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                                    String keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());

                                    StringBuilder keyword2 = new StringBuilder();
                                    keyword2.append(repairCourse.getSchoolDate() + "会进行调课");
                                    StringBuilder remark = new StringBuilder();
                                    remark.append("如有疑问，请与老师联系");
                                    List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                                    iWecharsBindService.wxCalOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                                } else {
                                    //班级里的调课学生
                                    StringBuilder first = new StringBuilder();
                                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”");
                                    String keyword1 = "";
                                    if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                                        keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                                    } else {
                                        //String teacherName =  studentGradeMapper.getTeacherNameForGradeId(studentGrade.getGradeId());
                                        keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();

                                    }

                                    StringBuilder keyword2 = new StringBuilder();
                                    keyword2.append(repairCourse.getSchoolDate()+ "会进行调课");
                                    StringBuilder remark = new StringBuilder();
                                    remark.append("如有疑问，请与老师联系");
                                    List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                                    iWecharsBindService.wxCalOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                                }
                            }
                        }


                    }
                } else if (repairCourse.getSchedulingType().equals(2)) {
                    Integer yearAndQuarter = Integer.parseInt(repairCourse.getYearPart() + "" + repairCourse.getQuarter());
                    Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(repairCourse.getSchoolId(), repairCourse.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, repairCourse.getLessonType());
                    if (residueCourseCount > 0) {
                        Student student = studentMapper.selectById(repairCourse.getStudentId());
                        if (student != null) {
                            StringBuilder first = new StringBuilder();
                            first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”");

                            String keyword1 = "";
                            if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                                keyword1 = this.replaceGradeName(repairCourse.getGradeName(),repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                            } else {
                                keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();
                                try {
                                    RecordCourse recordCourse = studentGradeMapper.getLastReadingGrade(repairCourse.getYearPart(), repairCourse.getQuarter(), repairCourse.getSchoolId(), repairCourse.getSubjectsId(), repairCourse.getStudentId());
                                    String gradeName = recordCourse.getGradeName();
                                    gradeName = this.replaceGradeName(gradeName, recordCourse.getTeacherName(),student.getName(), repairCourse.getSubjectsName());
                                    keyword1 = gradeName;
                                } catch (Exception e) {
                                }
                            }

                            StringBuilder keyword2 = new StringBuilder();
                            keyword2.append(repairCourse.getSchoolDate()+ "会进行调课");
                            StringBuilder remark = new StringBuilder();
                            remark.append("如有疑问，请与老师联系");
                            List<String> opendIdList = iWecharsBindService.getSendOpenid(repairCourse.getStudentId());
                            iWecharsBindService.wxCalOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                        }
                    }
                }
            } catch (Exception e) {

            }
        }
    }


    private String replaceGradeName(String gradeName,String teacherName, String studentName, String subjectsName) {
        String keyword1 = gradeName;
        if (keyword1.contains("【" + teacherName + "】")) {
            keyword1 = keyword1.replace("【" + teacherName + "】", "【" + studentName + "】" + subjectsName);
        } else if (keyword1.contains("【" + subjectsName + "】")) {
            keyword1 = keyword1.replace("【" + subjectsName + "】", "【" + studentName + "】" + subjectsName);
        } else if (keyword1.contains(teacherName)) {
            keyword1 = keyword1.replace(teacherName, studentName);
            keyword1 += subjectsName;
        } else {
            keyword1 = "【" + teacherName + "】" + subjectsName + keyword1;
        }
        return keyword1;
    }

}
